package com.jiexinyun.JdbcUtil;

import com.jiexinyun.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Slf4j
public class Main {

    public static void main(String[] args) {
        // 源数据库（SQL Server 2008 R2）
        String sourceUrl = "jdbc:sqlserver://192.168.0.102:1433;databaseName=wisestudio_001_2016;schemaName=dbo";
        String sourceUser = "sa";
        String sourcePassword = "110";

        // 目标数据库（PostgreSQL 14）
        String targetUrl = "jdbc:postgresql://192.168.0.102:5432/biaozhunjian?currentSchema=dbmain&characterEncoding=UTF-8";
        String targetUser = "biaozhunjian";
        String targetPassword = "Biaozhunjian@123456!";

        String schema = "dbo";      // SQL Server 的 schema
        String tableName = "tt"; // 要复制的表名

        Connection sourceConn = null;
        Connection targetConn = null;
        try {
            // 获取源表结构
            sourceConn = JdbcUtil.getConnection(sourceUrl, sourceUser, sourcePassword);
            List<ColumnInfo> columns = TableStructureCopier.getTableColumns(sourceConn, schema, tableName);

            if(CommonUtils.isEmpty(columns)) {
                log.info("源表不存在！！");
                return;
            }
            // 生成 PostgreSQL DDL
            String ddl = TableStructureCopier.generatePostgresqlDDL(tableName, columns);
            System.out.println("生成的DDL:\n" + ddl);

            // 在目标数据库建表
            targetConn = JdbcUtil.getConnection(targetUrl, targetUser, targetPassword);
            TableStructureCopier.executeDDL(targetConn, ddl);

            System.out.println("表结构复制完成！");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (sourceConn!= null) {
                JdbcUtil.closeConnection(sourceConn);
            }
            if (targetConn!= null) {
                JdbcUtil.closeConnection(targetConn);
            }
        }
    }

}
